package com.absorbx.commons;

import javax.servlet.ServletContext;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.web.context.WebApplicationContext;

public class ServletContextSupportQuartzJobBean extends QuartzJobBean {
	private static final String APPLICATION_CONTEXT_KEY = "applicationContext";

	@Override
	protected void executeInternal(JobExecutionContext arg0)
			throws JobExecutionException {

	}

	protected ApplicationContext getApplicationContext(
			JobExecutionContext context) throws Exception {
		ApplicationContext appCtx = null;

		appCtx = (ApplicationContext) context.getScheduler().getContext().get(
				APPLICATION_CONTEXT_KEY);

		if (appCtx == null) {
			throw new JobExecutionException(
					"No application context available in scheduler context for key \""
							+ APPLICATION_CONTEXT_KEY + "\"");
		}
		return appCtx;
	}

	protected ServletContext getServletContext(ApplicationContext appCtx)
			throws Exception {
		WebApplicationContext webCtx = null;
		ServletContext servletContext = null;
		if (appCtx instanceof WebApplicationContext) {
			webCtx = (WebApplicationContext) appCtx;
			servletContext = webCtx.getServletContext();

		}
		return servletContext;
	}

}
